<template>
  <div class="module-wrap border-l border-[#ffffff1a]">
    <div class="title-wrap config title-wrap_1 warn">
      <span class="title">近期预警统计</span>
      <div class="option tabs">
        <span
          v-for="(item, index) in list"
          :key="index"
          :class="{ active: isActive == item.value }"
          @click="() => onClick(item)"
          >{{ item.label }}</span
        >
      </div>
    </div>
    <div id="chart" ref="chartRef"></div>
  </div>
</template>

<script lang="tsx" setup>
import { onMounted, ref } from 'vue';
import * as echarts from 'echarts';
import 'echarts/theme/macarons';
import { recentAlarmStatistics } from '../api';

const isActive = ref('1');
const list = [
  { label: '近7天', value: '1' },
  { label: '近30天', value: '2' },
  { label: '近1年', value: '3' },
];
let chart: any;
const chartRef = ref();
const init = async () => {
  const res = await recentAlarmStatistics({ dayType: isActive.value });
  const xData = [];
  const deviceAlarm = [];
  const earthquakeAlarm = [];
  const eventAlarm = [];
  const pointAlarm = [];
  for (const item of res.data) {
    xData.push(item.forDate);
    deviceAlarm.push(item.deviceAlarmNum);
    earthquakeAlarm.push(item.earthquakeAlarmNum);
    eventAlarm.push(item.eventAlarmNum);
    pointAlarm.push(item.pointAlarmNum);
  }

  if (chart) chart.clear();
  chart = echarts.init(chartRef.value);
  const option = {
    tooltip: {
      trigger: 'axis',
    },
    color: ['#3bc1fd', '#f7ab65', '#3cfbc1', '#fd7589'],
    legend: {
      right: '4%',
      data: ['设备离线告警', '地震触发告警', '区域触发告警', '测点触发告警'],
      textStyle: {
        color: '#fff',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      data: xData,
      axisLine: {
        lineStyle: {
          color: 'rgba(255,255,255,.6)',
        },
      },
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          color: 'rgba(255,255,255,.26)',
        },
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(255,255,255,.6)',
        },
      },
    },
    series: [
      {
        name: '设备离线告警',
        type: 'line',
        symbolSize: 10,
        data: deviceAlarm,
      },
      {
        name: '地震触发告警',
        type: 'line',
        symbolSize: 10,
        data: earthquakeAlarm,
      },
      {
        name: '区域触发告警',
        type: 'line',
        symbolSize: 10,
        data: eventAlarm,
      },
      {
        name: '测点触发告警',
        type: 'line',
        symbolSize: 10,
        data: pointAlarm,
      },
    ],
  };
  chart.setOption(option);
  addEventListener(
    'resize',
    () => {
      chart.resize();
    },
    false,
  );
};
onMounted(() => {
  init();
});

const onClick = (record) => {
  isActive.value = record.value;
  init();
};
</script>
